<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Log;

/**
 * 示例接口
 */
class Callback extends Api {

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 无需登录的接口
     * 
     */
    public function wx() {
        Vendor('wxpay.WxPay');
        $wxpay = new \WxPay();
        $result = $wxpay->notify();

        if ($result) {
            // 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单id
            $saveData['transaction_id'] = $result['transaction_id'];
            $saveData['paytime'] = time();
            $saveData['amount'] = number_format($result['total_fee'] / 100, 2);
            $saveData['status'] = 1;

            \think\Db::name('recharge')->where(['out_trade_no' => $result['out_trade_no']])->update($saveData);

            $business_id = \think\Db::name('recharge')->where(['out_trade_no' => $result['out_trade_no']])->value('business_id');

            \think\Db::name('business_wallet')->where(['business_id' => $business_id])->setInc('cash_amount', number_format($result['total_fee'] / 100, 2));

            $wallet_id = \think\Db::name('business_wallet')->where(['business_id' => $business_id])->value('wallet_id');

            $wallet_log['change_amount'] = number_format($result['total_fee'] / 100, 2);
            $wallet_log['wallet_id'] = $wallet_id;
            $wallet_log['change_type'] = 0;
            $wallet_log['change_matters'] = 10;
            $wallet_log['createtime'] = time();

            \think\Db::name('business_wallet_log')->insert($wallet_log);
//            $businessWalletLog = model('BusinessWalletLog');
//            $businessWalletLog->data($wallet_log);
//            $businessWalletLog->save();
        }
    }

    /**
     * 需要登录的接口
     * 
     */
    public function test2() {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     * 
     */
    public function test3() {
        $this->success('返回成功', ['action' => 'test3']);
    }

}
